<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noodp"/><title>TensorFlow2.1入门学习笔记(4)——神经网络计算 | Yasin&#39;s Blog</title><meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content=""/>
<meta name="twitter:title" content="TensorFlow2.1入门学习笔记(4)——神经网络计算"/>
<meta name="twitter:description" content=""/><meta name="twitter:creator" content="@wangyuexin8"/><meta name="Description" content="KEEP KWARKING"><meta property="og:title" content="TensorFlow2.1入门学习笔记(4)——神经网络计算" />
<meta property="og:description" content="前面已经学习了有关TensorFlow的一些常用库，以及相关数据的处理方式，下面就是有关神经网络计算的学习笔记。主要学习的资料西安科技大学：" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://blog.aimoon.top/calculate/" /><meta property="og:image" content="https://blog.aimoon.top/images/favicon.svg"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2020-05-11T01:37:39&#43;08:00" />
<meta property="article:modified_time" content="2021-03-29T11:34:14&#43;08:00" /><meta property="og:site_name" content="Yasin&#39;s Blog" />

<meta name="application-name" content="YASIN">
<meta name="apple-mobile-web-app-title" content="YASIN"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/favicon.svg" type="image/x-icon"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://blog.aimoon.top/calculate/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "TensorFlow2.1入门学习笔记(4)——神经网络计算",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/blog.aimoon.top\/calculate\/"
        },"image": ["https:\/\/blog.aimoon.top\/images\/cover.png"],"genre": "posts","keywords": "calculate, 神经网络","wordCount":  2788 ,
        "url": "https:\/\/blog.aimoon.top\/calculate\/","datePublished": "2020-05-11T01:37:39+08:00","dateModified": "2021-03-29T11:34:14+08:00",
        "publisher": {
            "@type": "Person",
            "name": "Wang Yuexin", "image": [
            {
            "@type": "ImageObject",
            "url": "https:\/\/blog.aimoon.top\/images\/avatars.png"
            }
            ]},"author": {
                "@type": "Person",
                "name": "Wang Yuexin"
            },"description": ""
    }
    </script><script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [{
            "@type": "ListItem",
            "position": 1,
            "name": "主页",
            "item": "https:\/\/blog.aimoon.top"
        },{
            "@type": "ListItem",
            "position": 2,
            "name": "TF2.1学习笔记",
            "item": "https://blog.aimoon.top/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"
        },{
                "@type": "ListItem",
                "position": 3,
                "name": "TensorFlow2.1入门学习笔记(4)——神经网络计算"
            }]
    }
</script></head>
    <body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('light' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'light' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header>
    <div class="desktop header" id="header-desktop">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="Yasin&#39;s Blog" class="header-logo logo-svg">Yasin&#39;s Blog</a>
            </div>
            <div class="menu">
                <nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul class="menu-inner"><li>
                            <a class="menu-item" href="/posts/"> 目录 </a>
                        </li><li>
                            <a class="menu-item" href="/tags/"> 标签 </a>
                        </li><li>
                            <a class="menu-item" href="/categories/"> 归档 </a>
                        </li><li>
                            <a class="menu-item" href="/comments/"> 留言 </a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" rel="noopener noreffer" target="_blank"> 主页 </a>
                        </li></ul>
                </nav><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="search……" id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <span class="svg-icon icon-search"></span>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <span class="svg-icon icon-cancel"></span>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <span class="svg-icon icon-loading"></span>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <span class="svg-icon icon-moon"></span>
                </a>
            </div>
        </div>
    </div><div class="mobile header" id="header-mobile">
        <div class="header-container">
            <div class="header-wrapper">
                <div class="header-title">
                    <a href="/" title="Yasin&#39;s Blog" class="header-logo">Yasin&#39;s Blog</a>
                </div>
                <div class="menu-toggle" id="menu-toggle-mobile">
                    <span></span><span></span><span></span>
                </div>
            </div>
            <div class="menu" id="menu-mobile"><div class="search-wrapper">
                        <div class="search mobile" id="search-mobile">
                            <input type="text" placeholder="search……" id="search-input-mobile">
                            <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                                <span class="svg-icon icon-search"></span>
                            </a>
                            <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                                <span class="svg-icon icon-cancel"></span>
                            </a>
                            <span class="search-button search-loading" id="search-loading-mobile">
                                <span class="svg-icon icon-loading"></span>
                            </span>
                        </div>
                        <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                            取消
                        </a>
                    </div><nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul><li>
                            <a class="menu-item" href="/posts/" title="">目录</a>
                        </li><li>
                            <a class="menu-item" href="/tags/" title="">标签</a>
                        </li><li>
                            <a class="menu-item" href="/categories/" title="">归档</a>
                        </li><li>
                            <a class="menu-item" href="/comments/" title="">留言</a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" title="" rel="noopener noreffer" target="_blank">主页</a>
                        </li></ul>
                </nav>
                <a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <span class="svg-icon icon-moon"></span>
                </a></div>
        </div>
    </div><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div></header><main class="main">
<div class="container content-article page-toc theme-classic"><div class="toc" id="toc-auto">
            <div class="toc-title">目录</div>
            <div class="toc-content" id="toc-content-auto"></div>
        </div>
    

    
    
    <article>
    

        <header class="header-post">

            

            
            <div class="post-title">

                    <div class="post-all-meta">
                        <nav class="breadcrumbs">
    <ol>
        <li><a href="/">主页 </a></li><li><a href="/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">TF2.1学习笔记 </a></li><li>TensorFlow2.1入门学习笔记(4)——神经网络计算</li>
    </ol>
</nav>
                        <h1 class="single-title flipInX">TensorFlow2.1入门学习笔记(4)——神经网络计算</h1><div class="post-meta summary-post-meta"><span class="post-category meta-item">
                                <a href="/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"><span class="svg-icon icon-folder"></span>TF2.1学习笔记</a>
                            </span><span class="post-meta-date meta-item">
                                <span class="svg-icon icon-clock"></span><time class="timeago" datetime="2020-05-11">2020-05-11</time>
                            </span><span class="post-meta-words meta-item">
                                <span class="svg-icon icon-pencil"></span>约 2788 字
                            </span>
                            <span class="post-meta-reading meta-item">
                                <span class="svg-icon icon-stopwatch"></span>预计阅读 6 分钟
                            </span>
                        </div>

                    </div>

                </div>

                </header>

        <div class="article-post toc-start">

            <div class="content-block content-block-first content-block-position">

                <div class="post single"><div class="details toc" id="toc-static"  data-kept="">
                        <div class="details-summary toc-title">
                            <span>目录</span>
                        </div>
                        <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#1张量tensor的生成">1.张量(Tensor)的生成</a></li>
        <li><a href="#2常用函数">2.常用函数</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
                    </div><p>前面已经学习了有关TensorFlow的一些常用库，以及相关数据的处理方式，下面就是有关神经网络计算的学习笔记。主要学习的资料西安科技大学：<a href="https://www.icourse163.org/learn/XUST-1206363802#/learn/announce" target="_blank" rel="noopener noreffer">神经网络与深度学习——TensorFlow2.0实战</a>，北京大学：<a href="https://www.icourse163.org/learn/PKU-1002536002#/learn/announce" target="_blank" rel="noopener noreffer">人工智能实践Tensorflow笔记</a></p>
<!-- more -->
<h3 id="1张量tensor的生成" class="headerLink"><a href="#1%e5%bc%a0%e9%87%8ftensor%e7%9a%84%e7%94%9f%e6%88%90" class="header-mark"></a>1.张量(Tensor)的生成</h3><p><strong>张量可以表示0阶到n阶数组（列表）</strong>
张量：多维数组、多维列表
阶：张量的维数</p>
<table>
<thead>
<tr>
<th>维数</th>
<th>阶</th>
<th>名字</th>
<th>例子</th>
</tr>
</thead>
<tbody>
<tr>
<td>0-D</td>
<td>0</td>
<td>标量	scalar</td>
<td>s=1 2 3</td>
</tr>
<tr>
<td>1-D</td>
<td>0</td>
<td>向量	vector</td>
<td>v=[1, 2, 3]</td>
</tr>
<tr>
<td>2-D</td>
<td>0</td>
<td>矩阵	matrix</td>
<td>m=[[1, 2, 3],[4 ,5 ,6]]</td>
</tr>
<tr>
<td>n-D</td>
<td>0</td>
<td>张量	tensor</td>
<td>t=[[[(n个“[”)</td>
</tr>
</tbody>
</table>
<p><strong>数据类型</strong></p>
<ol>
<li>tf.int,tf.float……
tf.int32,	tf.float32,	tf.float64</li>
<li>tf.bool
tf.constant([True,False])</li>
<li>tf.string
tf.constant(&ldquo;Hello,world!&quot;)
<strong>创建一个张量</strong></li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># tf.constant(张量内容，dtype=数据类型(可选))</span>

<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">5</span><span class="p">],</span><span class="n">dtype</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">int64</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="o">.</span><span class="n">dtype</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510171226594.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510171226594.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>将numpy的数据类型转换为Tensor数据类型</strong>
tf.convert_to_tensor(数据名, dtype=数据类型(可选))</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">5</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">convert_to_tensor</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">int64</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510173300828.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510173300828.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>创建特殊张量</strong></p>
<ol>
<li>创建全为0的张量
tf.zeros([个数]维度)</li>
<li>创建全为1的张量
tf.ones([行, 列]维度)</li>
<li>chuangjian全为指定值的张量
tf.fill([n,m,j,k……]维度，指定值)</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">ones</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">fill</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mi">5</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a:&#34;</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;b:&#34;</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;c:&#34;</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510174859624.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510174859624.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>正态分布随机数</strong></p>
<ol>
<li>生成正态分布的随机数，默认均值为0，标准差为1
tf.random.normal(维度，mean=均值，stddev=标准差)</li>
<li>生成截断式正态分布的随机数
tf.random.truncated_normal(维度, mean=均值, stddev=标准差)
保证了生成的随机数在$(\mu-2\sigma,\mu+2\sigma)$之内
$\mu:均值, \sigma:标准差$
标准差计算公式: $\sigma = \sqrt[][\frac{\sum_{i=1}^n{(x_i-\overline{x})^2}}{n}]$</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>

<span class="n">d</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="n">mean</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">stddev</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;d:&#34;</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">truncated_normal</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="n">mean</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">stddev</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;e:&#34;</span><span class="p">,</span> <span class="n">e</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/2020051018355851.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/2020051018355851.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>生成均匀分布随机数 [minval,maxval)</strong>
tf.random.uniform(维度, minval=最小值, maxval=最大值)</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="n">minval</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">maxval</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;f:&#34;</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510184028200.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510184028200.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h3 id="2常用函数" class="headerLink"><a href="#2%e5%b8%b8%e7%94%a8%e5%87%bd%e6%95%b0" class="header-mark"></a>2.常用函数</h3><ul>
<li>强制tensor转换为该数据类型
tf.cast(张量名,dtype=数据类型)</li>
<li>计算张量维度上的最小值
tf.reduce_min(张量名)</li>
<li>计算张量维度上的最大值
tf.reduce_min(张量名)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">x1</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">2.</span><span class="p">,</span> <span class="mf">3.</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">float64</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;x1:&#34;</span><span class="p">,</span> <span class="n">x1</span><span class="p">)</span>
<span class="n">x2</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">int32</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;x2&#34;</span><span class="p">,</span> <span class="n">x2</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;minimum of x2：&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_min</span><span class="p">(</span><span class="n">x2</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;maxmum of x2:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_max</span><span class="p">(</span><span class="n">x2</span><span class="p">))</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510185305665.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510185305665.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>理解axis
在一个二维张量或数组中,可以通过调整axis等于1或者1来控制执行维度
axis=0代表跨行(经度,down),而axis=1代表跨列(维度,across)
如果不指定axis,则所有元素参与运算</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510190227789.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510190227789.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>计算张量沿指定维度的平均值
tf.reduce_mean(张量名, axis=操作轴)</li>
<li>计算张量沿指定维度的和
tf.reduce_sum(张量名, axis=操作轴)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span> 
<span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]])</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;x:&#34;</span><span class="p">,</span><span class="n">x</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;mean of axis=0:&#34;</span><span class="p">,</span><span class="n">tf</span><span class="o">.</span><span class="n">reduce_mean</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span>	<span class="c1">#计算每一列的均值</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;sum of axis=1:&#34;</span><span class="p">,</span><span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">))</span>	<span class="c1">#计算每行的和</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510191309762.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510191309762.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>tf.Variable(初始值)
将变量标记为&quot;可训练&quot;的,被标记的变量会在反向传播中记录梯度信息.神经网络训练中,常用该函数标记待训练参数
例如:w = tf.Variable(tf.random.noaml([2,2],mean=2,stddev=1))
就可以在反向传播过程中通过梯度下降更新参数w</li>
</ul>
<p><strong>TensorFlow中的数学运算</strong>
PS: 只有维度相同的张量才可以做四则运算</p>
<ul>
<li>对应元素的四则运算:
tf.add(张量1,张量2,张量3&hellip;&hellip;)
tf.subtract(张量1,张量2,张量3&hellip;&hellip;)
tf.multiply(张量1,张量2,张量3&hellip;&hellip;)
tf.divide(张量1,张量2,张量3&hellip;&hellip;)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">ones</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">fill</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mf">3.</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a:&#34;</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;b:&#34;</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a+b:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a-b:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a*b:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;b/a:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">divide</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="p">))</span>
</code></pre></td></tr></table>
</div>
</div><p>运算结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510193156565.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510193156565.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>平方,次方与开方:
tf.aquare(张量1,张量2,张量3&hellip;&hellip;)
tf.pow(张量1,张量2,张量3&hellip;&hellip;)
tf.sqrt(张量1,张量2,张量3&hellip;&hellip;)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">fill</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="mf">3.</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a:&#34;</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a的3次方:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a的平方:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">square</span><span class="p">(</span><span class="n">a</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a的开方:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">a</span><span class="p">))</span>
</code></pre></td></tr></table>
</div>
</div><p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510193512693.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510193512693.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>矩阵乘:
tf.matmul(张量1,张量2,张量3&hellip;&hellip;)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">ones</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">])</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">fill</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mf">3.</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a:&#34;</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;b:&#34;</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a*b:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">))</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510193909341.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510193909341.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>将输入特征/标签配对,构建数据集</strong></p>
<ul>
<li>tf.data.Dataset.from_tensor_slices((输入特征,标签))
(Numpy和Tensor格式都可以用该语句读入数据)</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">features</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">12</span><span class="p">,</span><span class="mi">23</span><span class="p">,</span><span class="mi">10</span><span class="p">,</span><span class="mi">17</span><span class="p">])</span>
<span class="n">labels</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">])</span>
<span class="n">dataset</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="o">.</span><span class="n">from_tensor_slices</span><span class="p">((</span><span class="n">features</span><span class="p">,</span><span class="n">labels</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="n">dataset</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">dataset</span><span class="p">:</span>
	<span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/2020051019513099.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/2020051019513099.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure>
<strong>求导运算:<font color=red>tf.GradientTape()</font></strong></p>
<p>with结构记录计算过程,gradient求出张量的梯度
例如:
$$\frac{\partial\omega^2}{\partial\omega}=2\omega=2\ast3.0=6.0$$</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">GradientTape</span><span class="p">()</span> <span class="k">as</span> <span class="n">tape</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">(</span><span class="mf">3.0</span><span class="p">))</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="n">grad</span> <span class="o">=</span> <span class="n">tape</span><span class="o">.</span><span class="n">gradient</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">grad</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510210144421.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510210144421.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>enumerate(列表名)</strong>
enumerate是python的内建函数,可以遍历每个元素(如列表,元组或字符串),组合为:<font color=orange>索引	元素</font>,常在for循环中使用</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">seq</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">]</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">element</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果:</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510211407134.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510211407134.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>独热编码:<font color=red>tf.one_hot()</font></strong></p>
<p>tf.one_hot(待转换数据,depth=分几类)
在分类问题中,常用独热码做标签
标记类别:1表示是;0表示非</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">classes</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">labels</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">])</span>  <span class="c1"># 输入的元素值最小为0，最大为2</span>
<span class="n">output</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">one_hot</span><span class="p">(</span><span class="n">labels</span><span class="p">,</span> <span class="n">depth</span><span class="o">=</span><span class="n">classes</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;result of labels1:&#34;</span><span class="p">,</span> <span class="n">output</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200510212434299.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200510212434299.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>将输出结果转换为概率分布：tf.nn.softmax()</strong>
数学表达式：<font color=red>$Softmax(y_i)=\frac{e^y_i}{\sum_{j=0}^ne^y_i}$</font>
可以使n个分类的n个输出（$y_0,y_1,……y_{n-1}$）符合概率分布
$\forall x P(X=x)\in[0,1]且\sum_xP(X=x)=1$</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mf">1.01</span><span class="p">,</span> <span class="mf">2.01</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.66</span><span class="p">])</span>
<span class="n">y_pro</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;After softmax, y_pro is:&#34;</span><span class="p">,</span> <span class="n">y_pro</span><span class="p">)</span>  <span class="c1"># y_pro 符合概率分布</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;The sum of y_pro:&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">y_pro</span><span class="p">))</span>  <span class="c1"># 通过softmax后，所有概率加起来和为1</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200511011532391.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200511011532391.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>参数自更新assign_sub()</strong></p>
<ul>
<li>复制操作，更新参数的值并返回。</li>
<li>调用assign_sub前，先用tf.Variable定义为变量w为可训练（可自更新）
w.assign_sub(w要自减的内容)</li>
</ul>
<p>$w-=1$</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">w</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="n">w</span><span class="o">.</span><span class="n">assign_sub</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;w:&#34;</span><span class="p">,</span><span class="n">w</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/202005110124570.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/202005110124570.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>返回指定维度的最大值tf.argmax()</strong>
返回张量沿指定维度最大值的<font color=red>索引</font>
tf.argmax(张量名，axis=操作轴)</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">test</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">8</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">2</span><span class="p">]])</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;test:</span><span class="se">\n</span><span class="s2">&#34;</span><span class="p">,</span> <span class="n">test</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;每一列的最大值的索引：&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">test</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span>  <span class="c1"># 返回每一列最大值的索引</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;每一行的最大值的索引&#34;</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">test</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">))</span>  <span class="c1"># 返回每一行最大值的索引</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：





<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200511013211719.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200511013211719.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><em><strong><a href="https://blog.csdn.net/moonoa/article/details/106045962" target="_blank" rel="noopener noreffer">通过前面的基础知识，下面可以构建一个简单的神经网络——鸢尾花分类问题</a></strong></em></p>
<p><strong><font size=5><a href="https://www.cnblogs.com/moonspace/p/12867300.html" target="_blank" rel="noopener noreffer">博客园链接</a></font></strong></p>
</div><footer>
                        <div class="post">


<div class="post-share"><div class="share-link">
        <a class="share-icon share-twitter" href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://blog.aimoon.top/calculate/" data-title="TensorFlow2.1入门学习笔记(4)——神经网络计算" data-via="wangyuexin8" data-hashtags="calculate,神经网络"><span class="svg-social-icon icon-twitter"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-facebook" href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://blog.aimoon.top/calculate/" data-hashtag="calculate"><span class="svg-social-icon icon-facebook"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-whatsapp" href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://blog.aimoon.top/calculate/" data-title="TensorFlow2.1入门学习笔记(4)——神经网络计算" data-web><span class="svg-social-icon icon-whatsapp"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-blogger" href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://blog.aimoon.top/calculate/" data-title="TensorFlow2.1入门学习笔记(4)——神经网络计算" data-description=""><span class="svg-social-icon icon-blogger"></span></a>
    </div></div>

<div class="footer-post-author">
    <div class="author-avatar"><a href="https://aimoon.top" target="_blank"><img alt="Undergraduate Student of Artificial Intelligence 😜" src="https://blog.aimoon.top/images/avatars.png"></a></div>
    <div class="author-info">
        <div class="name"><a href="https://aimoon.top" target="_blank">Wang Yuexin</a></div>
        <div class="number-posts">Undergraduate Student of Artificial Intelligence 😜</span></div>
    </div>
</div><div class="post-tags"><a href="/tags/calculate/" class="tag">calculate</a><a href="/tags/%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C/" class="tag">神经网络</a></div></div>
                </footer></div>
        <div id="toc-final"></div>
        </div>

    
    </article>
    <section class="page single comments content-block-position">
        <h1 class="display-hidden">Комментарии</h1><div id="comments"><div id="disqus_thread" class="comment" style="padding-top: 1.5rem"></div>
            <noscript>
                Please enable JavaScript to view the comments powered by <a href="https://disqus.com/?ref_noscript">Disqus</a>.
            </noscript></div></section></div>

</main><footer class="footer">
        <div class="footer-container"><div class="footer-line"><div><span id="timeDate">正在烧脑计算建站时间...</span><span id="times"></span><script>var now = new Date();function createtime(){var grt= new Date("05/20/2020 00:00:00");now.setTime(now.getTime()+250);days = (now - grt ) / 1000 / 60 / 60 / 24;dnum = Math.floor(days);hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);hnum = Math.floor(hours);if(String(hnum).length ==1 ){hnum = "0" + hnum; }minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);mnum = Math.floor(minutes);if(String(mnum).length ==1 ){mnum = "0" + mnum;}seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);snum = Math.round(seconds);if(String(snum).length ==1 ){snum = "0" + snum;}document.getElementById("timeDate").innerHTML = "&nbsp"+dnum+"&nbsp天";document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";}setInterval("createtime()",250);</script></div></div><div class="footer-line"><i class="svg-icon icon-copyright"></i><span>2020 - 2021</span><span class="author">&nbsp;<a href="https://aimoon.top" target="_blank">Yasin</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span><span class="icp-splitter">&nbsp;|&nbsp;</span><br class="icp-br"/>
                    <span class="icp"><a href="https://blog.pangao.vip/icp/xmoon.info">🧑ICP证000000号</a></span></div>
        </div>
    </footer></div>

        <aside id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="svg-icon icon-arrow-up"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="svg-icon icon-comments-fixed"></i>
            </a>
        </aside><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script src="https://yasin5.disqus.com/embed.js" defer></script><script src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script src="https://cdn.jsdelivr.net/npm/lunr@2.3.8/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="https://cdn.jsdelivr.net/npm/twemoji@13.0.0/dist/twemoji.min.js"></script><script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/mhchem.min.js"></script><script src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":30,"type":"lunr"},"twemoji":true};</script><script src="/js/theme.min.js"></script><script>
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

	        ga('create', 'UA-167439955-2', 'auto');
	        ga('set', 'anonymizeIp', true);
	        ga('send', 'pageview');
	    </script></body>
</html>
